package com.littlebee.storysuper.activity;

import android.Manifest;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.jpush.JsonElement;
import com.google.gson.jpush.annotations.Expose;
import com.google.gson.jpush.annotations.SerializedName;
import com.littlebee.storysuper.BaseApplication;
import com.littlebee.storysuper.R;
import com.littlebee.storysuper.adapter.ChatMsgViewAdapter;
import com.littlebee.storysuper.entry.User;
import com.littlebee.storysuper.utils.Constant;
import com.littlebee.storysuper.utils.LogUtils;
import com.littlebee.storysuper.utils.NetWorkUtils;
import com.littlebee.storysuper.utils.SoundMeter;
import com.littlebee.storysuper.utils.Utils;
import com.zss.library.PermissionCallBack;
import com.zss.library.activity.BaseActivity;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.FileUtils;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import cn.jpush.im.android.api.ContactManager;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetUserInfoListCallback;
import cn.jpush.im.android.api.content.MessageContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.enums.ContentType;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.enums.MessageDirect;
import cn.jpush.im.android.api.enums.MessageStatus;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.api.BasicCallback;

public class ChatActivity extends BaseActivity implements View.OnClickListener, GestureDetector.OnGestureListener {
    private GestureDetector detector;

    private Button mBtnSend;
    private TextView mBtnRcd;
    //private Button mBtnBack;
    private EditText mEditTextContent;
    private RelativeLayout mBottom;
    private ListView mListView;
    private ChatMsgViewAdapter mAdapter;
    private List<Message> mDataArrays = new ArrayList<Message>();
    private boolean isShosrt = false;
    private LinearLayout voice_rcd_hint_loading, voice_rcd_hint_rcding,
            voice_rcd_hint_tooshort;
    private ImageView img1, sc_img1;
    private SoundMeter mSensor;
    private View rcChat_popup;
    private LinearLayout del_re;
    private ImageView chatting_mode_btn, volume;
    private boolean btn_vocie = false;
    private int flag = 1;
    private Handler mHandler = new Handler();
    private String voiceName;
    private long startVoiceT, endVoiceT;
    private String[] msgArray = new String[]{"有人就有恩怨", "有恩怨就有江湖", "人就是江湖", "你怎么退出？ ", "生命中充满了巧合", "两条平行线也会有相交的一天。"};

    private String[] dataArray = new String[]{"2012-10-31 18:00",
            "2012-10-31 18:10", "2012-10-31 18:11", "2012-10-31 18:20",
            "2012-10-31 18:30", "2012-10-31 18:35"};
    private final static int COUNT = 6;
    private String fileName;
    float y1 = 0;
    float y2 = 0;

    @Override
    public int getLayoutResId() {
        return R.layout.chat;
    }

    @Override
    public void initView() {
        super.initView();
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        detector = new GestureDetector(ChatActivity.this, this);

        mListView = (ListView) findViewById(R.id.listview);
        mBtnSend = (Button) findViewById(R.id.btn_send);
        mBtnRcd = (TextView) findViewById(R.id.btn_rcd);
        mBtnSend.setOnClickListener(this);
        mBottom = (RelativeLayout) findViewById(R.id.btn_bottom);
        chatting_mode_btn = (ImageView) this.findViewById(R.id.ivPopUp);
        volume = (ImageView) this.findViewById(R.id.volume);
        rcChat_popup = this.findViewById(R.id.rcChat_popup);
        img1 = (ImageView) this.findViewById(R.id.img1);
        sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);
        del_re = (LinearLayout) this.findViewById(R.id.del_re);
        voice_rcd_hint_rcding = (LinearLayout) this
                .findViewById(R.id.voice_rcd_hint_rcding);
        voice_rcd_hint_loading = (LinearLayout) this
                .findViewById(R.id.voice_rcd_hint_loading);
        voice_rcd_hint_tooshort = (LinearLayout) this
                .findViewById(R.id.voice_rcd_hint_tooshort);
        mSensor = new SoundMeter();
        mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);

        //语音文字切换按钮
        chatting_mode_btn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                if (btn_vocie) {
                    mBtnRcd.setVisibility(View.GONE);
                    mBottom.setVisibility(View.VISIBLE);
                    btn_vocie = false;
                    chatting_mode_btn
                            .setImageResource(R.drawable.chatting_setmode_msg_btn);

                } else {
                    mBtnRcd.setVisibility(View.VISIBLE);
                    mBottom.setVisibility(View.GONE);
                    chatting_mode_btn
                            .setImageResource(R.drawable.chatting_setmode_voice_btn);
                    btn_vocie = true;
                }
            }
        });

        mBtnRcd.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                boolean ret = detector.onTouchEvent(event);
                if (!ret) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        y1 = event.getY();
                        LogUtils.i("XHX", "录音3");
                        mBtnRcd.setText("松开 结束");
                        mBtnRcd.setBackgroundResource(R.drawable.rect_corner_white_custom1);
                        rcChat_popup.setVisibility(View.VISIBLE);
                        voice_rcd_hint_loading.setVisibility(View.VISIBLE);
                        voice_rcd_hint_rcding.setVisibility(View.GONE);
                        voice_rcd_hint_tooshort.setVisibility(View.GONE);
                        mHandler.postDelayed(new Runnable() {
                            public void run() {
                                if (!isShosrt) {
                                    voice_rcd_hint_loading.setVisibility(View.GONE);
                                    voice_rcd_hint_rcding
                                            .setVisibility(View.VISIBLE);
                                }
                            }
                        }, 300);
                        //img1.setVisibility(View.VISIBLE);
                        del_re.setVisibility(View.GONE);
                        startVoiceT = System.currentTimeMillis();
                        voiceName = startVoiceT + ".amr";
                        start(voiceName);
                        flag = 2;
                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
                        y2 = event.getY();
                        mBtnRcd.setBackgroundResource(R.drawable.rect_corner_white_custom);
                        mBtnRcd.setText("按住 说话");

                        if (y1 - y2 > 50) {
                            rcChat_popup.setVisibility(View.GONE);
                            //img1.setVisibility(View.VISIBLE);
                            del_re.setVisibility(View.GONE);
                            stop();
                            flag = 1;
                            File file = new File(android.os.Environment.getExternalStorageDirectory() + "/"
                                    + voiceName);
                            if (file.exists()) {
                                file.delete();
                            }

                            LogUtils.i("XHX", "录音444444");
                        } else {
                            voice_rcd_hint_rcding.setVisibility(View.GONE);
                            stop();
                            endVoiceT = System.currentTimeMillis();
                            flag = 1;
                            int time = (int) ((endVoiceT - startVoiceT) / 1000);
                            LogUtils.i("XHX", "时长：开始" + startVoiceT + "；结束：" + endVoiceT + "时长：" + time);
                            if (time < 1) {
                                isShosrt = true;
                                voice_rcd_hint_loading.setVisibility(View.GONE);
                                voice_rcd_hint_rcding.setVisibility(View.GONE);
                                voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
                                mHandler.postDelayed(new Runnable() {
                                    public void run() {
                                        voice_rcd_hint_tooshort
                                                .setVisibility(View.GONE);
                                        rcChat_popup.setVisibility(View.GONE);
                                        isShosrt = false;
                                    }
                                }, 500);
                                return false;
                            }
                            LogUtils.i("XHX", "时长11111：");
                            User user=Utils.getUserEntry();
                            File file = new File(android.os.Environment.getExternalStorageDirectory()+"/"
                                    + voiceName);
                            try {
                                JMessageClient.createSingleVoiceMessage(mDataArrays.get(0).getFromUser().getUserName(), Constant.JPUSH_KEY, file,getAmrDuration(file.getAbsolutePath()));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            getInfo();
                        }
                    }
                }
                return true;
            }
        });
        chatting_mode_btn.performClick();

    }
    public static int getAmrDuration(String file) throws IOException {
        int leng = 0;
        MediaPlayer player = new MediaPlayer();
        player.setDataSource(file);
        player.prepare();
        leng = player.getDuration();
        player.release();
        player = null;
        return leng;
    }
    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        getInfo();

    }

    private void initMsg() {
        mEditTextContent.setText("");
        mAdapter = new ChatMsgViewAdapter(this, mDataArrays);
        mListView.setAdapter(mAdapter);
        mListView.setSelection(mListView.getCount() - 1);

    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.module_video_bg);
        toolbar.setTitle(getString(R.string.boby_call_txt));

    }


    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btn_send:
                send();
                break;
            case R.id.btn_back:
                finish();
                break;
        }
    }

    private void send() {
        String contString = mEditTextContent.getText().toString();
        sendMsg(contString);
//        if (contString.length() > 0) {
//            ChatMsgEntity entity = new ChatMsgEntity();
//            entity.setDate(getDate());
//            entity.setName("高富帅");
//            entity.setMsgType(false);
//            entity.setText(contString);
//
//            mDataArrays.add(entity);
//            mAdapter.notifyDataSetChanged();
//
//            mEditTextContent.setText("");
//
//            mListView.setSelection(mListView.getCount() - 1);
//        }
    }

    private void sendMsg(String contString) {
        Conversation mConversation = JMessageClient.getSingleConversation(mDataArrays.get(0).getFromUser().getUserName(), Constant.JPUSH_KEY);
        if (mConversation == null) {
            mConversation = Conversation.createSingleConversation(mDataArrays.get(0).getFromUser().getUserName(), Constant.JPUSH_KEY);
        }

        //构造message content对象
        TextContent textContent = new TextContent(contString);
        //设置自定义的extra参数
        textContent.setStringExtra(null, null);

        //创建message实体，设置消息发送回调。
        Message message = mConversation.createSendMessage(textContent, null);
        message.setOnSendCompleteCallback(new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                if (i == 0) {
                    Log.i("XHX", "JMessageClient.createSingleTextMessage" + ", responseCode = " + i + " ; LoginDesc = " + s);
                    Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_SHORT).show();
                } else {
                    Log.i("XHX", "JMessageClient.createSingleTextMessage" + ", responseCode = " + i + " ; LoginDesc = " + s);
                    Toast.makeText(getApplicationContext(), "发送失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //设置消息发送时的一些控制参数
        MessageSendingOptions options = new MessageSendingOptions();
        options.setRetainOffline(true);//是否当对方用户不在线时让后台服务区保存这条消息的离线消息
        options.setShowNotification(true);//是否让对方展示sdk默认的通知栏通知
        options.setCustomNotificationEnabled(false);//是否需要自定义对方收到这条消息时sdk默认展示的通知栏中的文字
//        if (false) {
//            options.setNotificationTitle(mEt_customNotifyTitle.getText().toString());//自定义对方收到消息时通知栏展示的title
//            options.setNotificationAtPrefix(mEt_customNotifyAtPrefix.getText().toString());//自定义对方收到消息时通知栏展示的@信息的前缀
//            options.setNotificationText(mEt_customNotifyText.getText().toString());//自定义对方收到消息时通知栏展示的text
//        }

        //发送消息
        JMessageClient.sendMessage(message, options);
        getInfo();
    }



    private static final int POLL_INTERVAL = 300;

    private Runnable mSleepTask = new Runnable() {
        public void run() {
            stop();
        }
    };
    private Runnable mPollTask = new Runnable() {
        public void run() {
            double amp = mSensor.getAmplitude();
            updateDisplay(amp);
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);

        }
    };

    private void start(String name) {
        mSensor.start(name);
        mHandler.postDelayed(mPollTask, POLL_INTERVAL);
    }

    private void stop() {
        mHandler.removeCallbacks(mSleepTask);
        mHandler.removeCallbacks(mPollTask);
        mSensor.stop();
        volume.setImageResource(R.drawable.ease_record_animate_02);
    }

    private void updateDisplay(double signalEMA) {

        switch ((int) signalEMA) {
            case 0:
            case 1:
                volume.setImageResource(R.drawable.ease_record_animate_02);
                break;
            case 2:
            case 3:
                volume.setImageResource(R.drawable.ease_record_animate_04);

                break;
            case 4:
            case 5:
                volume.setImageResource(R.drawable.ease_record_animate_07);
                break;
            case 6:
            case 7:
                volume.setImageResource(R.drawable.ease_record_animate_09);
                break;
            case 8:
            case 9:
                volume.setImageResource(R.drawable.ease_record_animate_11);
                break;
            case 10:
            case 11:
                volume.setImageResource(R.drawable.ease_record_animate_13);
                break;
            default:
                volume.setImageResource(R.drawable.ease_record_animate_14);
                break;
        }
    }


    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    /**
     * 获取好友列表
     */
    public void getInfo() {
        List<Conversation> conversationList = JMessageClient.getConversationList();
        if (conversationList != null&&conversationList.size()>0) {

            mDataArrays = conversationList.get(0).getAllMessage();
            if (mDataArrays != null) {
                initMsg();
            } else {
                Toast.makeText(ChatActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
            }

        } else {
            Toast.makeText(ChatActivity.this, "该用户没有会话", Toast.LENGTH_SHORT).show();
        }

    }




}
